<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;



class QuestionController extends Controller {

    public $data = array();

    public $goAuth = false;
    public $goReload = false;

    public function __construct(){
        session_start();
        $this->data['user_agent'] = $this->getUserAgent();

        if( empty($_SESSION['user_id']) ){
            $this->goAuth = true;
        }
    }



    //创建问题的页面
    function addQuestionPage(){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/question");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        //查找所有的topic
        $topics = DB::table('topic')
                        ->select('id','name')
                        ->where('is_deleted','=',0)
                        ->get();

        $this->data['topics'] = $topics;
        return view('add_question' , $this->data);
    }


    //创建问题
    function createQuestion(){
        if( !Input::has('title') ){
            return Response::json(['error'=>true , 'message'=>'提交问题的标题不能为空'] , 200);
        }
        if( !Input::has('description') ){
            return Response::json(['error'=>true , 'message'=>'提交问题的描述不能为空'] , 200);
        }
        if( !Input::has('topic') ){
            return Response::json(['error'=>true , 'message'=>'提交问题的话题分类'] , 200);
        }
        $user_id        = $_SESSION['user_id'];
        $title          = Input::get('title');
        $description    = Input::get('description');
        $topic          = Input::get('topic');

        $insert_arr = array(
            'title' => $title ,
            'description' => $description ,
            'topic_id' => $topic ,
            'creator_id' => $user_id ,
            'create_time' => date('Y-m-d H:i:s' , time())
            );
        $insert_id = DB::table('question')->insertGetId($insert_arr);
        if( $insert_id > 0 ){
            //默认添加关注
            $insert_att_arr = array(
                'user_id' => $user_id ,
                'question_id' => $insert_id ,
                'add_time' => date('Y-m-d H:i:s' , time())
                );
            DB::table('user_question')->insert( $insert_att_arr );
            return Response::json(['error'=>false , 'message'=>'问题提交成功'] , 200);
        }else{
            return Response::json(['error'=>true , 'message'=>'问题提交失败'] , 200);
        }
    }


    //显示单个问题详情
    function questionDetail($id){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/detail/$id");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'该问题不存在'] , 200);
        }
        $user_id = $_SESSION['user_id'];

        $result = DB::table('question')
                        ->select('question.id' , 'question.title' , 'question.description' , 'topic.id as topic_id' , 'topic.name as topic_name')
                        ->join('topic' , 'question.topic_id' , '=' , 'topic.id')
                        ->where('question.id' , '=' , $id)
                        ->where('question.is_deleted' , '=' , 0)
                        ->get();
        if( count($result) == 0 ){
            return Response::json(['error'=>true , 'message'=>'该问题不存在'] , 200);
        }

        $attentions = DB::table('user_question')->where('question_id','=',$id)->where('is_deleted','=',0)->count();

        //查找自己是否关注
        $self_attention = DB::table('user_question')
                                ->where('question_id','=',$id)
                                ->where('user_id','=',$user_id)
                                ->where('is_deleted','=',0)
                                ->get();
        $this->data['is_attention'] = count($self_attention) == 0 ? 0 : 1;

        //查找答案
        $answers = DB::table('answer')
                        ->select('answer.*','user.name','user.icon')
                        ->join('user','user.id','=','answer.creator_id')
                        ->where('answer.question_id','=',$id)
                        ->where('answer.is_deleted','=',0)
                        ->orderBy('answer.up' , 'DESC')
                        ->orderBy('answer.add_time' , 'DESC')
                        ->get();

        $this->data['question']             = $result;
        $this->data['attention_count']      = $attentions;
        $this->data['answers']              = $answers;
        $this->data['can_answer']           = isset($_SESSION['answer']) ? $_SESSION['answer'] : 0;

        $this->data['title']        = $result[0]->title;
        $this->data['description']  = $result[0]->description;

        return view('detail' , $this->data);
    }


    //获取单个话题下的所有的问题
    function singleTopicPage($id){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/topic/$id");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'该话题不存在'] , 200);
        }

        $topic = DB::table('topic')->where('id','=',$id)->get();
        if( count($topic) < 1 ){
            return Response::json(['error'=>true , 'message'=>'该话题不存在'] , 200);
        }

        $questions = DB::table('question')->where('topic_id','=',$id)->where('is_deleted','=',0)->get();

        if( count($questions) > 0 ){
            $question_id_arr = array();
            foreach( $questions as $key => $val ){
                $question_id_arr[] = $val->id;
            }
            $str = implode(',' , $question_id_arr);
            //查找回答
            $answers = DB::select("select
                                    question_id , count(question_id) as temp_count
                                    from
                                    answer
                                    where
                                    question_id in ($str)
                                    group by
                                    question_id
                                    ");
            //查找关注
            $attentions = DB::select("select
                                        question_id , count(question_id) as temp_count
                                        from
                                        user_question
                                        where
                                        question_id in ($str)
                                        group by
                                        question_id
                                        ");
            $id_to_answers = array();
            $id_to_attentions = array();
            foreach( $answers as $key => $val ){
                $id_to_answers[$val->question_id] = $val->temp_count;
            }
            foreach( $attentions as $key => $val ){
                $id_to_attentions[$val->question_id] = $val->temp_count;
            }
            $this->data['answers_count'] = $id_to_answers;
            $this->data['attentions_count'] = $id_to_attentions;
        }

        $this->data['topic'] = $topic;
        $this->data['questions'] = $questions;

        $this->data['title']        = "话题 : ".$topic[0]->name;
        $this->data['description']  = $topic[0]->description;

        return view('topic_details' , $this->data);
    }


    //最新问题
    function latestQuestion(){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/new_questions");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        $questions = DB::table('question')
                        ->select('question.id' , 'question.title')
                        ->where('is_deleted','=',0)
                        ->orderBy('create_time' , 'DESC')
                        ->get();

        if( count($questions) > 0 ){
            $question_id_arr = array();
            foreach( $questions as $key => $val ){
                $question_id_arr[] = $val->id;
            }
            $str = implode(',' , $question_id_arr);
            //查找回答
            $answers = DB::select("select
                                    question_id , count(question_id) as temp_count
                                    from
                                    answer
                                    where
                                    question_id in ($str)
                                    group by
                                    question_id
                                    ");
            //查找关注
            $attentions = DB::select("select
                                        question_id , count(question_id) as temp_count
                                        from
                                        user_question
                                        where
                                        question_id in ($str)
                                        group by
                                        question_id
                                        ");
            $id_to_answers = array();
            $id_to_attentions = array();
            foreach( $answers as $key => $val ){
                $id_to_answers[$val->question_id] = $val->temp_count;
            }
            foreach( $attentions as $key => $val ){
                $id_to_attentions[$val->question_id] = $val->temp_count;
            }
            $this->data['answers_count'] = $id_to_answers;
            $this->data['attentions_count'] = $id_to_attentions;
        }

        $this->data['questions'] = $questions;

        $this->data['title']        = "拾光问答";
        $this->data['description']  = "最新问题";


        return view('new_questions' , $this->data);
    }


    public $content = "";
    //搜索问题
    function searchQuestions(){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/");
            if( Input::has('content') ){
                $state      = urlencode("http://".env("APP_URL")."/search?content=".Input::get('content'));
            }
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        if( !Input::has('content') ){
            return Response::json(['error'=>true , 'message'=>'搜索内容不能为空'] , 200);
        }
        $this->content = Input::get('content');

        $questions = DB::table('question')->where('is_deleted','=',0);
        $questions = $questions->where(function($query){
            $query->where('title','like','%'.$this->content.'%');
            $query->orWhere('description','like','%'.$this->content.'%');
        });
        $questions = $questions->get();

        if( count($questions) > 0 ){
            $question_id_arr = array();
            foreach( $questions as $key => $val ){
                $question_id_arr[] = $val->id;
            }
            $str = implode(',' , $question_id_arr);
            //查找回答
            $answers = DB::select("select
                                    question_id , count(question_id) as temp_count
                                    from
                                    answer
                                    where
                                    question_id in ($str)
                                    group by
                                    question_id
                                    ");
            //查找关注
            $attentions = DB::select("select
                                        question_id , count(question_id) as temp_count
                                        from
                                        user_question
                                        where
                                        question_id in ($str)
                                        group by
                                        question_id
                                        ");
            $id_to_answers = array();
            $id_to_attentions = array();
            foreach( $answers as $key => $val ){
                $id_to_answers[$val->question_id] = $val->temp_count;
            }
            foreach( $attentions as $key => $val ){
                $id_to_attentions[$val->question_id] = $val->temp_count;
            }
            $this->data['answers_count'] = $id_to_answers;
            $this->data['attentions_count'] = $id_to_attentions;
        }

        $this->data['questions'] = $questions;
        $this->data['content'] = $this->content;

        if( Input::has('type') && Input::get('type') == 'ajax' ){
            $return_arr = array();
            if( isset($this->data['answers_count']) ){
                $return_arr['answers_count'] = $this->data['answers_count'];
            }
            if( isset($this->data['attentions_count']) ){
                $return_arr['attentions_count'] = $this->data['attentions_count'];
            }
            $return_arr['questions'] = $questions;
            $return_arr['content'] = $this->content;
            return Response::json(['error'=>false , 'result'=>$return_arr] , 200);
        }

        $this->data['title']        = "拾光问答";
        $this->data['description']  = "问题搜索";

        return view('search_question' , $this->data);
    }

}
